# -*- coding: utf-8 -*-

import math
import json
import numpy as np
import re
import logging

def set_basic_log_config():

    logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s -   %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

def ilogging(msg, logger, level=logging.INFO):
        logger.log(level, msg)

def strtobool(str_val):
    """Convert a string representation of truth to true (1) or false (0).

    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    str_val = str_val.lower()
    if str_val in ('y', 'yes', 't', 'true', 'on', '1'):
        return True
    elif str_val in ('n', 'no', 'f', 'false', 'off', '0'):
        return False
    else:
        raise ValueError("invalid truth value %r" % (str_val,))


def pad_sents(sents, pad_token):
    """
    @param sents (list[list[str]]): list of sentences
    @param pad_token (str): padding token
    @return sents_padded (list[list[str]]): list of sentences where shorted sents are padded out
    """
    max_length = max([len(sents[i]) for i in range(len(sents))])
    for sent in sents:
        if len(sent) < max_length:
            leftovers = [pad_token] * (max_length - len(sent))
            sent.extend(leftovers)
    sents_padded = sents
    return sents_padded

def read_corpus(file_path):
    corpus = json.load(open(file_path, 'r'))
    data = [list(c) for c in corpus]    # List[List[str]]
    return data

def comply_rule(s):
    """
    return whether the s comply to the rule of poem
    """
    lens = [len(t) for t in s.split('|')]
    if len(lens) == 1:
        return lens[0] <=7
    else:
        if lens[0] != 5 and lens[0] != 7:
            return False
        for i in range(1, len(lens)-1):
            if lens[i] != lens[0]:
                return False
        return lens[-1] <= lens[0]

def poem_format(poem):
    assert isinstance(poem, list)
    if poem[0] == '<s>':
        poem = poem[1:]
    if poem[-1] == '</s>':
        poem = poem[:-1]
    return poem
